<?php


namespace Rebuild\Config;


use Symfony\Component\Finder\Finder;

class ConfigFactory
{
    public function __invoke()
    {
        $bashPath = BASE_PATH . "/config";
        $configFile = $this->readConfig($bashPath . '/config.php');
        $autoloadConfigFile = $this->readPath([$bashPath . '/autoload']);
        $configs = array_merge_recursive($configFile, ...$autoloadConfigFile);
        return new Config($configs);
    }

    protected function readConfig(string $string): array
    {
        $config = require $string;
        if (empty($config)) {
            return [];
        }
        return $config;
    }

    protected function readPath(array $dirs): array
    {
        $configs = [];
        $finder = new Finder();
        $finder->files()->in($dirs)->name("*.php");
        foreach ($finder as $file) {
            $configs[] = [
                $file->getBasename('.php') => require $file->getRealPath(),
            ];
        }
        return $configs;
    }
}